package com.sk.cardeal.zxing.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.ScanGoodAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.entity.InSaveEntity;
import com.sk.cardeal.entity.OutSaveEntity;
import com.sk.cardeal.entity.ScanGoodEntity;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.zxing.camera.CameraManager;
import com.sk.cardeal.zxing.decoding.CaptureActivityHandler;
import com.sk.cardeal.zxing.decoding.InactivityTimer;
import com.sk.cardeal.zxing.decoding.Intents;
import com.sk.cardeal.zxing.decoding.RGBLuminanceSource;
import com.sk.cardeal.zxing.view.ViewfinderView;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;


/**
 * Initial the camera
 *
 * @author Ryan.Tang
 */
public class CaptureActivity extends BaseActivity implements Callback, HandleDataCallBack, View.OnClickListener {

    private static final int REQUEST_CODE_SCAN_GALLERY = 100;

    private TextView tv_tip, finish_scan;
    private RecyclerView data_ryc;

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private ImageView back;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private ProgressDialog mProgress;
    private String photo_path;
    private Bitmap scanBitmap;
    //	private Button cancelScanButton;
    public static final int RESULT_CODE_QR_SCAN = 0xA1;
    public static final String INTENT_EXTRA_KEY_QR_SCAN = "qr_scan_result";

    private LoadingDialog loadingDialog;
    private String lackpurchaseId = "";
    private ScanGoodAdapter adapter;
    private String type;

    private List<ScanGoodEntity.ReturnObjectBean> alldataList = new ArrayList<>();

    @Override
    protected int getContentView() {
        return R.layout.activity_scan;
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("onCreate", "onCreate");
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        lackpurchaseId = getIntent().getStringExtra("code");
        type = getIntent().getStringExtra("type");
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        //ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
        CameraManager.init(getApplication());
        viewfinderView = findViewById(R.id.viewfinder_content);
        tv_tip = findViewById(R.id.tv_tip);
        finish_scan = findViewById(R.id.finish_scan);
        data_ryc = findViewById(R.id.data_ryc);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);

        finish_scan.setOnClickListener(this);

        data_ryc.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new ScanGoodAdapter(R.layout.item_scan_good, alldataList);
        data_ryc.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.scanner_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()){
//            case R.id.scan_local:
//                //打开手机中的相册
//                Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); //"android.intent.action.GET_CONTENT"
//                innerIntent.setType("image/*");
//                Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
//                this.startActivityForResult(wrapperIntent, REQUEST_CODE_SCAN_GALLERY);
//                return true;
//        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SCAN_GALLERY:
                    //获取选中图片的路径
                    Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
                    if (cursor.moveToFirst()) {
                        photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    }
                    cursor.close();

                    mProgress = new ProgressDialog(CaptureActivity.this);
                    mProgress.setMessage("正在扫描...");
                    mProgress.setCancelable(false);
                    mProgress.show();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Result result = scanningImage(photo_path);
                            if (result != null) {
                                Intent resultIntent = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putString(INTENT_EXTRA_KEY_QR_SCAN, result.getText());
                                resultIntent.putExtras(bundle);
                                CaptureActivity.this.setResult(RESULT_CODE_QR_SCAN, resultIntent);

                            } else {
                                Message m = handler.obtainMessage();
                                m.what = R.id.decode_failed;
                                m.obj = "Scan failed!";
                                handler.sendMessage(m);
                            }
                        }
                    }).start();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 扫描二维码图片的方法
     *
     * @param path
     * @return
     */
    public Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        Hashtable<DecodeHintType, String> hints = new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取原大小
        scanBitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false; // 获取新的大小
        int sampleSize = (int) (options.outHeight / (float) 200);
        if (sampleSize <= 0)
            sampleSize = 1;
        options.inSampleSize = sampleSize;
        scanBitmap = BitmapFactory.decodeFile(path, options);
        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        try {
            return reader.decode(bitmap1, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.v("onCreate", "onResume");
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scanner_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * Handler scan result
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        //FIXME
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
        } else {
            loadingDialog.show();
            AppApi.partsDeails(type, resultString, lackpurchaseId, CaptureActivity.this, 0, CaptureActivity.this);
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.show();
        switch (tag){
            case 0:
                mHandler.postDelayed(runnable, 2000);
                loadingDialog.cancelDialog();
                ScanGoodEntity scanGoodEntity = JSON.parseObject(result, ScanGoodEntity.class);
                ScanGoodEntity.ReturnObjectBean entity = scanGoodEntity.getReturnObject();

                if (alldataList.size() > 0) {
                    boolean iscontain = false;
                    for (ScanGoodEntity.ReturnObjectBean dataBean : alldataList) {

                        if (entity.getGoodsCode().equals(dataBean.getGoodsCode())) {
                            SnackUtils.showError(mRootView, "该配件已扫描过！");
                            iscontain = true;
                            break;
                        }

                        if (dataBean.getVin().equals(entity.getVin()) && dataBean.getQuality() == entity.getQuality()) {
                            iscontain = true;
                            dataBean.setScanCount(dataBean.getScanCount() + 1);
                        }
                    }
                    if (!iscontain) {
                        entity.setScanCount(1);
                        alldataList.add(entity);
                    }

                } else {
                    entity.setScanCount(1);
                    alldataList.add(entity);
                }
                adapter.notifyDataSetChanged();
                int num = 0;
                for (ScanGoodEntity.ReturnObjectBean dataBean : alldataList) {
                    num += dataBean.getScanCount();
                }
                tv_tip.setText("已扫描" + num + "件");
                break;
            case 10:
                Toast.makeText(mContext,"保存成功！",Toast.LENGTH_SHORT).show();
                break;
            case 20:
                Toast.makeText(mContext,"保存成功！",Toast.LENGTH_SHORT).show();
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }


    Handler mHandler = new Handler();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            if (handler != null) {
                try {
                    handler.restartPreviewAndDecode(); // 实现多次扫描
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (type) {
            case "1":
                InSaveEntity inSaveEntity = new InSaveEntity();
                inSaveEntity.setType(1);
                inSaveEntity.setUserid(MyUtils.getUser(mContext).getId());
                inSaveEntity.setLackpurchaseId(lackpurchaseId);
                List<String> stringArrayList = new ArrayList<>();
                for(ScanGoodEntity.ReturnObjectBean dataBean : alldataList){
                    stringArrayList.add(dataBean.getPartCode());
                }
                inSaveEntity.setGoodsCode_List(stringArrayList);
                loadingDialog.show();
                AppApi.inListSave(inSaveEntity,CaptureActivity.this,10,CaptureActivity.this);
                break;
            case "2":
                OutSaveEntity outSaveEntity = new OutSaveEntity();
                outSaveEntity.setType(1);
                outSaveEntity.setUserid(MyUtils.getUser(mContext).getId());
                outSaveEntity.setLackpurchaseId(lackpurchaseId);
                List<String> stringList = new ArrayList<>();
                for(ScanGoodEntity.ReturnObjectBean dataBean : alldataList){
                  stringList.add(dataBean.getPartCode());
                }
                outSaveEntity.setGoodsCode_List(stringList);
                loadingDialog.show();
                AppApi.outListSave(outSaveEntity,CaptureActivity.this,10,CaptureActivity.this);
                break;
        }
    }
}